package com.xja.security.service.imp;

import com.xja.security.entity.Admin;
import com.xja.security.service.AdminService;
import com.xja.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 周广瑞
 * @date 2022/4/12 14:49
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.login(username);
        if (admin ==null)
            throw  new UsernameNotFoundException("用户不能为空");
        //获取登录用户的角色列表
        List<String> roleList = roleService.findRoleByAid(admin.getaId());
        //把数据库中的 角色列表信息和security角色信息对象转换
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String roleName : roleList) {
            authorityList.add(new SimpleGrantedAuthority(roleName));
        }
        return new User(username,admin.getaPass(),authorityList);
    }
}
